<template>
	<view class="container">
		<view class="user-info">
			<image class="avatar" src="@/assets/images/Cat-logo.png"></image>
			<text class="name">Wade Warren</text>
		</view>

		<!-- 我的宠物 -->
		<view class="pet-list">
			<view v-for="(pet, index) in petList" :key="pet.id" class="pet" :class="{
				active: selectedPetId === pet.id,
			}" @click="onClickPet(pet.id,index)" @longpress="onLongPress(index)">
				<image class="avatar" :src="pet.avatar"></image>
				<view class="info">
					<text class="ageYear">{{ pet.ageYear }} Years old</text>
					<text class="name">{{ pet.name }}</text>
				</view>
				<view class="call" :class="{ 'to-back': showDeleteIndex == index }" @click="toDetail(pet.id)">Call
				</view>
				<view class="delete" :class="{ 'to-front': showDeleteIndex == index }" @click="deletePet(pet.id)">删除
				</view>
			</view>
			<!-- 新增 -->
			<view class="pet add">
				<image class="avatar" src="@/assets/svgs/claw-qian-pink.svg"></image>
				<view class="call" @click="showPopup">新增</view>
				<!-- <view class="call" @click="toDetail">测试</view> -->
			</view>
		</view>

		<!-- 我的计划 -->
		<Plan :data="selectedPet ? selectedPet.plan : []"  :petId="petList[petIndex].id" @add="addPlan" @delete="deletePlan" @done="donePlan"></Plan>
		<!-- <Plan :data="petList[petIndex] ? petList[petIndex] : []"  @add="addPlan" @delete="deletePlan" @done="donePlan"></Plan> -->
		
		<!-- <Feeding :data="selectedPet ? selectedPet.feedings : []" @add="addFeeding" @delete="deleteFeeding" @done="doneFeeding"></Feeding> -->

		<!-- 新增宠物 -->
		<MyPopup :show="isShowPopup" @hide="hidePopup">
			<view class="popup">
				<view class="title">新增</view>
				<view class="form">
					<MyForm :model="newPet" :rules="rules" ref="myFormRef">
						<MyFormItem label="名称" prop="name">
							<!-- <MyInput maxlength="6" v-model="newPet.name" /> -->
							<MyInput maxlength="6" @updateModelValue="updateModelValue" :modelValue="newPet.name"
								obj="name" />
						</MyFormItem>
						<!-- <MyFormItem label="年龄">
							<slider name="ageYear" min="0.5" max="20" step="0.5" class="slider" block-size="22"
								activeColor="@my-color-primary" show-value :value="newPet.ageYear"></slider>
						</MyFormItem> -->
						<MyFormItem label="岁" prop="ageYear">
							<!-- <MyInput maxlength="6" v-model="newPet.name" /> -->
							<!-- maxlength:输入框字段限制长度 -->
							<MyInput maxlength="2" @updateModelValue="updateModelValue" :modelValue="newPet.ageYear"
								obj="ageYear" />
						</MyFormItem>
						<MyFormItem label="月" prop="ageMonth">
							<!-- <MyInput maxlength="6" v-model="newPet.name" /> -->
							<!-- maxlength:输入框字段限制长度 -->
							<MyInput maxlength="2" @updateModelValue="updateModelValue" :modelValue="newPet.ageMonth"
								obj="ageMonth" />
						</MyFormItem>
						<MyFormItem label="品种" prop="breed">
							<!-- <MyInput maxlength="6" v-model="newPet.name" /> -->
							<!-- maxlength:输入框字段限制长度 -->
							<!-- 需要什么在这里加， 这几个字段得和数据库字段对应-->
							<MyInput maxlength="10" @updateModelValue="updateModelValue" :modelValue="newPet.breed"
								obj="breed" />
						</MyFormItem>
						<MyFormItem label="体重" prop="wright">
							<!-- <MyInput maxlength="6" v-model="newPet.name" /> -->
							<!-- maxlength:输入框字段限制长度 -->
							<!-- 需要什么在这里加， 这几个字段得和数据库字段对应-->
							<MyInput maxlength="10" @updateModelValue="updateModelValue" :modelValue="newPet.wright"
								obj="wright" />
						</MyFormItem>
						
						
						<!-- <MyFormItem label="类别">
							<MyRadioGroup :modelValue="newPet.category" @updateModelValue="updateModelValue">
								<MyRadio value="cat" label="猫猫" @updateModelValue="updateModelValue" obj="category"
									:selectValue="newPet.category" />
								<MyRadio value="dog" label="狗狗" @updateModelValue="updateModelValue" obj="category"
									:selectValue="newPet.category" />
							</MyRadioGroup>
						</MyFormItem> -->
						<button class="submit" @click="handleNewPetSubmit">完成</button>
					</MyForm>
				</view>
			</view>
		</MyPopup>

		<MyMessage ref="myMessageRef"></MyMessage>

		<MyDialog ref="myDialog"></MyDialog>
	</view>
</template>

<script>
	import {
		addPet
	} from '@/api/backend'
	import http from '@/api/backend'
	import {
		mapState,
		mapActions,
		mapMutations
	} from 'vuex';
	import cat from '@/assets/images/cat.png';
	import MyPopup from '@/components/MyPopup/MyPopup.vue'
	import MyDialog from '@/components/MyDialog/MyDialog.vue'
	import MyMessage from '@/components/MyMessage/MyMessage.vue'
	import MyForm from '@/components/MyForm/MyForm.vue'
	import MyRadioGroup from '@/components/MyRadioGroup/MyRadioGroup.vue'
	import MyRadio from '@/components/MyRadio/MyRadio.vue'
	import MyInput from '@/components/MyInput/MyInput.vue'
	import MyFormItem from '@/components/MyFormItem/MyFormItem.vue'
	import Plan from '@/components/Plan/Plan.vue'
	import Feeding from '@/components/Feeding/Feeding.vue'
	
	


	export default {
		data() {
			return {
				rules: {
					name: [{
						required: true,
						message: "请填写名称"
					}],
				},
				isShowPopup: false,
				isShowTip: false,
				showDeleteIndex: -1,
				petIndex:-1,
				selectedPetId: "",
				newPet: {
					id: "1",
					// avatar: cat,
					name: "1",
					breed:"1",
					ageYear: "1",
					ageMonth:"1",
					// sex: "母",
					// category: "cat",
					// color: "白",
					weight: "0.5",
					// plans: [],
					photoUrl: "http://dummyimage.com/400x400"
				},
			};
		},
		components: {
			MyPopup,
			MyDialog,
			MyMessage,
			MyForm,
			MyRadioGroup,
			MyRadio,
			MyInput,
			MyFormItem,
			Plan
		},
		computed: {
			...mapState('pet', ['petList']),
			selectedPet() {
				// const str =  this.petList.find(pet => pet.id === this.selectedPetId) || null;
				const str = this.petList[this.petIndex]
				console.log(str.plan);
				return str
			},
		},
		async created() {
			await this.initPetList();
			
			if (this.petList.length) {
			// if (this.$store.state.pet.petList.length) {
				this.selectedPetId = this.petList[0].id;
				this.petIndex = 0

			}
			
		},
		methods: {
			...mapActions('pet', ['initPetList', 'deletePetById', 'addPetToLast', 'deletePetPlanById',
				'completePetPlanById', 'addPetPlanById'
			]),
			...mapMutations('pet',['deletePetPlan']),
			onLongPress(index) {
				uni.vibrateLong();
				if (this.showDeleteIndex === index) {
					this.showDeleteIndex = -1;
				} else {
					this.showDeleteIndex = index;
				}
			},
			updateModelValue(obj, val) {
				this.newPet[`${obj}`] = val
			},
			toDetail(id) {
				// 
				console.log(id);
				uni.navigateTo({
					url: `/pages/pet/detail?id=${id}`,
				});
				// if (id && this.getPetById(id)) {
				// 	uni.navigateTo({
				// 		url: `/pages/pet/detail?id=${id}`,
				// 	});
				// } else {
				// 	this.$refs.myMessageRef.show({
				// 		message: "查找不到该宠物信息",
				// 		type: "error",
				// 	});
				// }
			},
			showPopup() {
				this.isShowPopup = true;
			},
			hidePopup() {
				this.isShowPopup = false;
			},
			deletePet(id) {
				this.$refs.myDialog.open({
					title: "删除宠物信息",
					content: "确认删除该宠物信息？",
					confirm: () => {
						console.log(id);
						this.deletePetById(id);
						this.$refs.myMessageRef.show({
							message: `删除成功`,
						});
					},
				});
				this.showDeleteIndex = -1;
			},
			handleNewPetSubmit() {
				if (!this.newPet.name) {
					this.$refs.myMessageRef.show({
						type: 'error',
						message: '请输入必输项名称！',
					});
					return;
				}
				this.$refs.myFormRef.validate((valid) => {
					if (valid) {
						// 页面直接触发处理结果 - 第一种
						const param = {
							...this.newPet
						}
						// addPet(param).then((res) => {
						//   // 这里处理新增的结果
						//   if (res.status === 200) {
						// 	  this.petList.push({

						// 	  })
						// 	  // 成功之后在提示
						// 	  // this.$refs.myMessageRef.show({
						// 	  // 	message: "添加成功",
						// 	  // });
						// 	  this.hidePopup();
						//   }

						// });

						// 这个是触发actions里面的新增 - 第二种 -- 方便统一全局管理
						this.addPetToLast(this.newPet);
						this.hidePopup();
						this.$refs.myMessageRef.show({
							message: "添加成功",
						});

					}
				});
			},
			getPetPlanById(select,id){
				let result = {}
				this.petList[select].plan.forEach(item=>{
					if(item.id===id) result=item
				})
				
				return result
			},

			deletePlan(id) {
				this.$refs.myDialog.open({
					title: "删除计划",
					content: "确认删除该计划？",
					confirm: () => {
						const plan = this.getPetPlanById(this.petIndex, id);
						let title = "";
						if (plan) {
							title = plan.title;
						}
						// this.deletePetPlanById(this.selectedPetId, id);
						this.deletePlan(this.selectedPetId,id)
						this.$refs.myMessageRef.show({
							message: `删除【${title}】`,
						});
					},
				});
			},
			donePlan(id) {
				const plan = this.getPetPlanById(this.petIndex, id);
				let title = "";
				if (plan) {
					title = plan.title;
				}
				// this.completePetPlanById(this.selectedPetId, id);
				this.$refs.myMessageRef.show({
					message: `完成【${title}】`,
				});
			},
			onClickPet(id,index) {
				this.selectedPetId = id;
				this.petIndex  = index
				
				// http.queryPetEvent(id,{}).then((res)=>{
				// 	console.log(res);
				// })
				// console.log('选中',this.petList[this.petIndex]);
			},
			addPlan(plan) {
				console.log(plan);
				http.addPetEvent(this.selectedPetId, plan).then(()=>{
					console.log('添加成功');
				});
				this.$refs.myMessageRef.show({
					message: "添加成功",
				});
			},
		},
	};
</script>

<style lang="less" scoped>
	// 行为相关颜色
	@my-color-primary:#FFA500;
	@my-color-error: #ff4747;

	// 文字相关颜色
	@my-text-color: #303330;
	@my-text-color-grey: rgb(157, 155, 155);
	@my-text-color-grey-opacity: rgba(157, 155, 155, 0.5);

	// 背景相关
	@my-background-color: #eff3ff;

	.container {
		height: 100vh;
		background: @my-background-color;
		padding-top: 5rem;
		padding-top: 20px;
		box-sizing: border-box;

		.user-info {
			display: flex;
			align-items: center;
			margin: 0 1.5rem;
			margin-bottom: 1.5rem;

			.avatar {
				width: 3rem;
				height: 3rem;
				border-radius: 50%;
				margin-right: 1rem;
				background: @my-color-primary;
				box-shadow: 0px 2px 8px #FFA500;
			}

			.name {
				font-weight: bold;
				font-size: 1.5rem;
			}
		}

		.pet-list {
			display: flex;
			overflow: auto;
			padding: 0.5rem 1.5rem;
			margin-bottom: 1rem;
			align-items: center;

			.pet {
				min-width: 8rem;
				height: 12rem;
				display: flex;
				flex-direction: column;
				border-radius: 1.5rem;
				background-color: #fff;
				overflow: hidden;
				margin-right: 1rem;
				position: relative;
				box-shadow: 1px 1px 5px rgba(0, 0, 0, 0.1);
				transition: all 0.1s linear;

				.avatar {
					width: 100%;
					height: 50%;
				}

				.info {
					padding: 0.8rem;
					padding-bottom: 0;
					display: flex;
					flex-direction: column;

					.age {
						color: @my-text-color-grey;
						font-size: 0.8rem;
					}

					.name {
						font-weight: bold;
					}
				}

				.call,
				.delete {
					height: 2rem;
					text-align: center;
					line-height: 2rem;
					background: @my-color-primary;
					color: #fff;
					margin: 0.5rem 0.8rem;
					border-radius: 1rem;
					font-size: 0.8rem;
					transition: all ease-in-out 0.5s;
					position: absolute;
					width: 80%;
					bottom: 0;
					z-index: 50;
				}

				.delete {
					z-index: 40;
					opacity: 0;
					transform: rotateY(-180deg);
					background: @my-color-error;
				}

				.to-back {
					opacity: 0;
					transform: rotateY(180deg);
					transition: all ease-in-out 0.5s;
				}

				.to-front {
					opacity: 1;
					transform: rotateY(0deg);
					transition: all ease-in-out 0.5s;
					z-index: 60;
				}

				&.active {
					transform: scale(1.05);
					box-shadow: 1px 1px 5px rgba(170, 105, 255, 0.5);
				}
			}

			.add {
				margin-right: 0;

				.avatar {
					margin-top: 2rem;
				}

				.call {
					margin-top: 2rem;
				}
			}
		}

		.popup {
			padding-bottom: 0;
			width: 60vw;

			.title {
				font-weight: bold;
				font-size: 1.2rem;
				color: @my-color-primary;
				margin-bottom: 1rem;
			}

			.form {
				margin-bottom: 1rem;

				.tip {
					margin: 0.2rem 0;
					font-size: 0.8rem;
					color: @my-color-error;
				}

				.submit {
					background: @my-color-primary;
					color: #fff;
					font-size: 1rem;
					border-radius: 0.8rem;
					margin-top: 2rem;

					&::after {
						border: none;
					}
				}
			}
		}
	}
</style>